<template>
	<div class="app">
		<block v-if="$util.shieldReview()">
			<div class="dynamic-form">
				<app-cell title="标题图">
					<div slot="value">
						<uploader class="upload_box" :size="150" :num="1" :imgList.sync="form.images" />
					</div>
				</app-cell>
				<app-input-all placeholder="请输入内容" title="标题" v-model="form.title" />
				<app-input-all placeholder="请输入内容" title="公众号链接" v-model="form.url" />
			</div>
			<footer class="app-footer" @click="savedynamic">保存</footer>
			<edit-alert ref="editAlert" />
		</block>
		<block v-else></block>
	</div>
</template>

<script>
import appInputAll from '@/components/app_input_all'
import appCell from '@/components/app_cell'
import EditAlert from '@/pages/components/editAlert'
import $apiCompany from '@/api/company'
import uploader from '@/components/App_uploader'
export default {
	name: 'addDynamic',
	components: {
		appInputAll,
		appCell,
		EditAlert,
		uploader
	},
	data() {
		return {
			form: {
				images: [],
				title: '',
				url: ''
			},
			query: {}
		}
	},
	onLoad(val) {
		this.query = {
			...val,
			editData: this.$util.isEmpty(val.editData) ? null : JSON.parse(val.editData)
		}
	},
	mounted() {
		if (this.query.status === 'edit' && !this.$util.isEmpty(this.query.editData)) {
			const editData = this.query.editData
			Object.keys(this.form).forEach(item => {
				if (item === 'images') {
					this.form.images.push(editData[item])
				} else {
					this.form[item] = editData[item]
				}
			})
		}
	},
	methods: {
		saveSuccee() {
			this.$refs.editAlert.editalert = true
		},
		add() {
			$apiCompany
				.addNews({
					...this.form,
					images: this.form.images[0],
					addtime: new Date()
				})
				.then(res => {
					if (res.status === 'success') {
						this.saveSuccee()
					} else {
						uni.showToast({
							title: res.errors.message,
							icon: 'none'
						})
					}
				})
		},
		edit() {
			$apiCompany
				.editNews({
					...this.form,
					images: this.form.images[0],
					addtime: new Date(),
					id: this.query.editData.id
				})
				.then(res => {
					if (res.status == 'success') {
						this.saveSuccee()
					} else {
						uni.showToast({
							title: res.errors.message,
							icon: 'none'
						})
					}
				})
		},
		savedynamic() {
			if (this.query.status == 'add') {
				this.add()
			} else {
				this.edit()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
	.dynamic-form {
		padding: 0 5%;
	}
	.upload_box {
		margin-top: 20px;
		float: right;
	}
</style>
